package com.whale.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Scroller;

import com.whale.R;

/**
 * 循环翻页插件
 * 
 * @author zhe.yangz 原作：Tinker
 * @createDate 2011-5-24 refactor 2011-07-27
 * @version v1.0.1
 */

public class FlipPageWidget extends ViewGroup {

	public static final int FLIP_DIRECTION_PRE = 1;
	public static final int FLIP_DIRECTION_NEXT = 2;

	private boolean isFlipPre = true;
	private boolean isFlipNext = true;

	private static final int INVALID_SCREEN = -1;
	private int mDefaultScreen;
	private boolean mFirstLayout = true;
	private int mCurrentScreen;
	private int mNextScreen = INVALID_SCREEN;

	private Scroller mScroller;
	// 记录了上次鼠标按下时的XY值，在ACTION_MOVE中赋值；
	private float mLastMotionX;
	private float mLastMotionY;
	// 记录触摸状态
	private final static int TOUCH_STATE_REST = 0;
	private final static int TOUCH_STATE_SCROLLING = 1;
	private int mTouchState = TOUCH_STATE_REST;
	public static int mDefaultSlop;
	public static int mTouchSlop; // 这个值表示需要滑动多少距离的时候才翻到下一页

	public int mDataIndex = 100; // 当前View中的数据在总数据所在位置
	private int mNextDataIndex = INVALID_SCREEN;
	private IFlipWidgetListener mListener;
	private boolean isAddFinish = false;
	private boolean isChangeScreen = false;

	public ListView lv_stream1; // 对应于MainStream的listview组件
	public ListView lv_stream2; // 对应于IncomingStream的listview组件

	/**
	 * Used to inflate the Workspace from XML.
	 */
	public FlipPageWidget(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	/**
	 * Used to inflate the Workspace from XML.
	 */
	public FlipPageWidget(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mDefaultScreen = 1;
		initView();
	}

	private void initView() {
		mScroller = new Scroller(getContext());
		mCurrentScreen = mDefaultScreen;

		final ViewConfiguration configuration = ViewConfiguration
				.get(getContext());
		mDefaultSlop = configuration.getScaledTouchSlop();
		mTouchSlop = mDefaultSlop * 3;

		LayoutInflater inflater = LayoutInflater.from(getContext());

		ViewGroup view = (ViewGroup) inflater.inflate(R.layout.stream, null,
				false);
		// lv_stream1 = (ListView) view.findViewById(R.id.lv_stream);
		addView(view);

		view = (ViewGroup) inflater.inflate(R.layout.stream, null, false);
		lv_stream1 = (ListView) view.findViewById(R.id.lv_stream);
		addView(view);

		view = (ViewGroup) inflater.inflate(R.layout.stream, null, false);
		lv_stream2 = (ListView) view.findViewById(R.id.lv_stream);
		addView(view);

		setViewId();
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			if ((isAddFinish)
					&& (mScroller.getCurrX() == (mScroller.getFinalX()))) {
				if (mNextDataIndex > mDataIndex) {
					scrollToNext(mNextDataIndex);
				} else if (mNextDataIndex < mDataIndex) {
					scrollToPrev(mNextDataIndex);
				}
				if (isChangeScreen) {
					if (mListener != null) {
						mListener.onFlipCompleted();
					}
					if (mNextScreen != INVALID_SCREEN) {
						mCurrentScreen = Math.max(0,
								Math.min(mNextScreen, getChildCount() - 1));
						mNextScreen = INVALID_SCREEN;
					}
				}
				isAddFinish = false;
			}
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * 绘制ViewGroup的View
	 */
	@Override
	public void dispatchDraw(Canvas canvas) {
		boolean restore = false;
		boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING
				&& mNextScreen == INVALID_SCREEN;
		// If we are not scrolling or flinging, draw only the current screen
		if (fastDraw) {
			final int count = getChildCount();
			for (int i = 0; i < count; i++) {
				drawChild(canvas, getChildAt(i), getDrawingTime());
			}
		} else {
			final long drawingTime = getDrawingTime();
			// If we are flinging, draw only the current screen and the target
			// screen
			if (mNextScreen >= 0 && mNextScreen < getChildCount()
					&& Math.abs(mCurrentScreen - mNextScreen) == 1) {
				drawChild(canvas, getChildAt(mCurrentScreen), drawingTime);
				drawChild(canvas, getChildAt(mNextScreen), drawingTime);
			} else {
				// If we are scrolling, draw all of our children
				final int count = getChildCount();
				for (int i = 0; i < count; i++) {
					drawChild(canvas, getChildAt(i), drawingTime);
				}
			}
		}
		if (restore) {
			canvas.restore();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View#onMeasure(int, int)
	 * 重写了父类的onMeasure()，主要功能是设置屏幕的显示大小。由每个child的measure()方法设置
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		final int width = MeasureSpec.getSize(widthMeasureSpec);
		final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		// 仅当ViewGroup为fill_parent才处于EXACTLY模式
		if (widthMode != MeasureSpec.EXACTLY) {
			throw new IllegalStateException(
					"Workspace can only be used in EXACTLY mode.");
		}

		final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		if (heightMode != MeasureSpec.EXACTLY) {
			throw new IllegalStateException(
					"Workspace can only be used in EXACTLY mode.");
		}

		// The children are given the same width and height as the workspace
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}

		if (mFirstLayout) {
			scrollTo(mCurrentScreen * width, 0);
			mFirstLayout = false;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.ViewGroup#onLayout(boolean, int, int, int, int)
	 * 重写了父类的onLayout()，主要功能是设置屏幕的显示位置。由child的layout()方法设置
	 */
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int childLeft = 0;
		int tempWidth = 0;
		// 设置布局，将子视图顺序横屏排列
		for (int i = 0; i < getChildCount(); i++) {
			final View child = getChildAt(i);
			if (child.getVisibility() != View.GONE) {
				final int childWidth = child.getMeasuredWidth();
				tempWidth = childWidth;
				childLeft = (mDataIndex + i - 1) * childWidth;
				child.layout(childLeft, 0, childLeft + childWidth,
						child.getMeasuredHeight());
			}
		}
		snapToScreen(mDataIndex, tempWidth);
	}

	@Override
	public boolean dispatchUnhandledMove(View focused, int direction) {
		if (direction == View.FOCUS_LEFT) {
			if (getCurrentScreen() > 0) {
				snapToScreen(getCurrentScreen() - 1);
				return true;
			}
		} else if (direction == View.FOCUS_RIGHT) {
			if (getCurrentScreen() < getChildCount() - 1) {
				snapToScreen(getCurrentScreen() + 1);
				return true;
			}
		}
		return super.dispatchUnhandledMove(focused, direction);
	}

	private int getCurrentScreen() {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == mDataIndex) {
				return i;
			}
		}
		return mCurrentScreen;
	}

	private int getNextScreen(int dataIndex) {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == dataIndex) {
				return i;
			}
		}
		return mNextScreen;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
	 * 重写了父类的onInterceptTouchEvent()，主要功能是在onTouchEvent()方法之前处理
	 * touch事件。包括：down、up、move事件。
	 * 当onInterceptTouchEvent()返回true时进入onTouchEvent()。
	 */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		final int action = ev.getAction();
		if ((action == MotionEvent.ACTION_MOVE)
				&& (mTouchState != TOUCH_STATE_REST)) {
			return true;
		}
		final float x = ev.getX();
		final float y = ev.getY();

		switch (action) {
		case MotionEvent.ACTION_MOVE:
			/*
			 * 记录xy与mLastMotionX、mLastMotionY差值的绝对值。xDiff和yDiff大于
			 * touchSlop时就认为界面拖动了足够大的距离，屏幕就可以移动了。
			 */
			final int xDiff = (int) Math.abs(x - mLastMotionX);
			final int yDiff = (int) Math.abs(y - mLastMotionY);
			final int touchSlop = mTouchSlop;
			boolean xMoved = (xDiff > touchSlop) && (xDiff >= 2 * yDiff);
			boolean yMoved = yDiff > touchSlop;
			if (xMoved || yMoved) {
				if (xMoved) {
					// Scroll if the user moved far enough along the X axis
					mTouchState = TOUCH_STATE_SCROLLING;
				}
			}
			break;
		case MotionEvent.ACTION_DOWN:
			// Remember location of down touch
			mLastMotionX = x;
			mLastMotionY = y;
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
					: TOUCH_STATE_SCROLLING;
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			// Release the drag
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		return mTouchState != TOUCH_STATE_REST;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View#onTouchEvent(android.view.MotionEvent)
	 * 主要功能是处理onInterceptTouchEvent()返回值为true时传递过来的touch事件
	 */
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		final int action = ev.getAction();
		final float x = ev.getX();

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}
			// Remember where the motion event started
			mLastMotionX = x;
			break;
		case MotionEvent.ACTION_MOVE:
			// 手指拖动屏幕的处理
			if ((mTouchState == TOUCH_STATE_SCROLLING) && ((!isAddFinish))) {
				// Scroll to follow the motion event
				final int deltaX = (int) (mLastMotionX - x);
				mLastMotionX = x;
				if (deltaX < 0) {
					if ((isFlipPre) && (getScrollX() > getWidth() * 100)) {
						scrollBy(Math.max(-1 * getScrollX(), deltaX), 0);
					}
				} else if (deltaX > 0) {
					final int availableToScroll = getWidth() * 101
							- getScrollX();
					if ((availableToScroll > 0) && (isFlipNext)) {
						scrollBy(Math.min(availableToScroll, deltaX), 0);
					}
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			// 弹起手指后，切换屏幕的处理
			if (mTouchState == TOUCH_STATE_SCROLLING) {
				snapToDestination();
			}
			mTouchState = TOUCH_STATE_REST;
			break;
		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
			break;
		default:
			break;
		}
		return true;
	}

	private void snapToDestination() {
		if (mListener != null) {
			mListener.onFlipStarted();
		}

		// 计算应该去哪个屏
		int whichScreen = mDataIndex;
		final int screenWidth = getWidth();
		final int factor1 = (getScrollX() + (screenWidth / 2)) / screenWidth;
		float factor2 = (getScrollX() + (screenWidth / 2.0f)) / screenWidth;
		final float factor3 = factor2 - factor1;
		int x = getScrollX();
		int x_ori = mDataIndex * screenWidth;
		if (x_ori < x) {
			// left
			if (factor3 > 0.75 || factor3 < 0.5) {
				whichScreen = mDataIndex + 1;
			}
		} else {
			// right
			if (factor3 > 0.5 || factor3 < 0.25) {
				whichScreen = mDataIndex - 1;
			}
		}

		snapToScreen(whichScreen);
	}

	void snapToScreen(int dataIndex) {
		if (!mScroller.isFinished())
			return;
		isAddFinish = true;
		mNextDataIndex = dataIndex;

		boolean changingScreens = dataIndex != mDataIndex;
		View focusedChild = getFocusedChild();
		if (focusedChild != null && changingScreens) {
			focusedChild.clearFocus();
		}
		final int cx = getScrollX(); // 启动的位置
		final int newX = dataIndex * getWidth(); // 最终停留的位置
		final int delta = newX - cx; // 滑动的距离，正值是往左滑<—，负值是往右滑—>
		mScroller.startScroll(cx, 0, delta, 0, Math.abs(delta) * 4);

		invalidate();
	}

	private void snapToScreen(int dataIndex, int width) {
		if (getFocusedChild() != null && dataIndex != this.mDataIndex) {
			getFocusedChild().clearFocus();
		}
		final int delta = dataIndex * width - getScrollX();
		mScroller.startScroll(getScrollX(), 0, delta, 0, 500);
		invalidate();
	}

	private void scrollToNext(int dataIndex) {
		if (!isFlipPre)
			isFlipPre = true;

		isChangeScreen = true;
		mNextScreen = getNextScreen(dataIndex);
		mCurrentScreen = getCurrentScreen();
		mDataIndex = dataIndex;

		if (isFlipNext) {
			View view = getChildAt(0);
			removeViewAt(0);
			addView(view, 2);
			setViewId();
			invalidate();
			// try {
			// Thread.currentThread();
			// Thread.sleep(5000);
			// } catch (InterruptedException ex) {
			// ex.printStackTrace();
			// }
		}
	}

	private void scrollToPrev(int dataIndex) {
		if (!isFlipNext)
			isFlipNext = true;

		isChangeScreen = true;
		mNextScreen = getNextScreen(dataIndex);
		mCurrentScreen = getCurrentScreen();
		mDataIndex = dataIndex;

		if (isFlipPre) {
			View view = getChildAt(2); // 2->1
			removeViewAt(2);
			addView(view, 0);
			setViewId();
			invalidate();
			// try {
			// Thread.currentThread();
			// Thread.sleep(5000);
			// } catch (InterruptedException ex) {
			// ex.printStackTrace(); // 抛出错误信息
			// }
		}
	}

	private void setViewId() {
		getChildAt(0).setId(mDataIndex - 1);
		getChildAt(1).setId(mDataIndex);
		getChildAt(2).setId(mDataIndex + 1);
	}

	public void addListener(IFlipWidgetListener listener) {
		this.mListener = listener;
	}

	public View getCurrentView() {
		if (mDataIndex == -1)
			return getChildAt(mDefaultScreen);

		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == (mDataIndex)) {
				return getChildAt(i);
			}
		}
		return null;
	}

	public View getPreView() {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == (mDataIndex - 1)) {
				return getChildAt(i);
			}
		}
		return null;
	}

	public View getNextView() {
		for (int i = 0; i < getChildCount(); i++) {
			if (getChildAt(i).getId() == (mDataIndex + 1)) {
				return getChildAt(i);
			}
		}
		return null;
	}

	public void switchToPage(int direction) {
		switch (direction) {
		case FLIP_DIRECTION_PRE:
			snapToScreen(mDataIndex - 1);
			break;
		case FLIP_DIRECTION_NEXT:
			snapToScreen(mDataIndex + 1);
			break;
		default:
			break;
		}
	}

	public void stopFlipPage(int direction) {
		switch (direction) {
		case FLIP_DIRECTION_PRE:
			isFlipPre = false;
			break;
		case FLIP_DIRECTION_NEXT:
			isFlipNext = false;
			break;
		default:
			break;
		}
	}

	public void startFlipPage(int direction) {
		switch (direction) {
		case FLIP_DIRECTION_PRE:
			isFlipPre = true;
			break;
		case FLIP_DIRECTION_NEXT:
			isFlipNext = true;
			break;
		default:
			break;
		}
	}
}